<template>
  <!-- 区总 -->
  <!-- 黑名单管理 -->
  <a-spin class="live-review" tip="加载中..." :spinning="isLoading">
    <!-- 筛选 -->
    <div class="filter">
      <div class="l search-box">
        <div>
          <span>站点：</span>
          <a-select
            allowClear
            style="width:160px;"
            showSearch
            :defaultActiveFirstOption="false"
            :filterOption="false"
            @search="getAllStation($event)"
            @change="changeLocation"
            v-model="search.locationId"
            placeholder="请选择站点"
            class="filter-select"
          >
            <a-select-option v-for="item in allStation" :key="item.id" :value="item.id">{{ item.city }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span>产品ID：</span>
          <a-input-search oninput="value = value.replace(/[^\d]/g, '')" style="width:240px;" placeholder="输入产品ID" allowClear v-model="search.bizProductId" @search="handleByQueryCond" />
        </div>
        <div>
          <span>抖音号：</span>
          <a-input-search type="text" style="width:240px;" placeholder="抖音号" allowClear v-model="search.douyinId" @search="handleByQueryCond" />
        </div>
      </div>
      <div class="r">
        <a-button type="link" style="margin-right:10px;color:#1d6fe9" @click="handleDownloadTemplate">下载模版</a-button>
      </div>
      <div class="r">
        <a-button style="margin-right:10px;background:#1d6fe9" type="primary" @click="fileVisible = true"><a-icon type="upload" />导入黑名单</a-button>
      </div>
      <!-- 导入黑名单弹窗 -->
      <a-modal v-model="fileVisible" title="导入黑名单" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
        <input type="file" ref="xlsFile" accept=".xls,.xlsx" @change="inputFileChange" />
      </a-modal>
      <div class="r">
        <a-button type="primary" style="margin-right:10px;background:#1d6fe9">下载模版</a-button>
      </div>
      <div class="r">
        <a-button type="primary" style="margin-right:10px;background:#1d6fe9">导入文件</a-button>
      </div>
      <div class="r">
        <a-button type="primary" style="margin-right:10px;background:#1d6fe9" @click="addBlacklistVisible = true">新增黑名单</a-button>
      </div>
      <div class="r">
        <a-button type="primary" @click="handleByQueryCond" style="background:#1d6fe9">查询</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="main-body">
      <a-table :columns="tableColumns" :pagination="false" :data-source="blacklist" :scroll="{ x: 900, y: tableHeight }" rowKey="id">
        <!-- 状态 -->
        <template slot="result" slot-scope="text, record">
          <div class="statu_box" v-if="record.result === 0">
            <p>失败</p>
            <a-popover trigger="click">
              <template slot="content">
                <p>{{ record.remark }}</p>
              </template>
              <a-icon class="zt_discrible_btn" type="question-circle" />
            </a-popover>
          </div>
          <p v-else>成功</p>
        </template>
        <!-- 操作按钮 -->
        <template slot="action" slot-scope="text, record">
          <a-popconfirm
            v-if="(record.cps > 0 && record.result === 1) || (record.cps === 0 && record.result === 0)"
            title="你确定要拉黑吗？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="confirmBlock(record.id)"
            @cancel="cancelBlock"
          >
            <a href="javascript:;">拉黑</a>
          </a-popconfirm>
          <a-popconfirm v-else title="你确定要解除吗？" ok-text="确定" cancel-text="取消" @confirm="confirmRelieve(record.id)" @cancel="cancelRelieve">
            <a href="javascript:;">解除黑名单</a>
          </a-popconfirm>
        </template>
      </a-table>
    </div>

    <!-- 新增产品弹窗 -->
    <a-modal v-model="addBlacklistVisible" title="新增黑名单" @ok="handleAddBlacklist" @cancel="addClose">
      <a-form-model :model="addBlacklistForm" ref="addBlacklistForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <a-form-model-item label="产品Id" prop="bizProductId" :rules="[{ required: true, trigger: 'change', message: '请填写产品id' }]">
          <a-input allowClear oninput="value = value.replace(/[^\d]/g, '')" v-model="addBlacklistForm.bizProductId" />
        </a-form-model-item>
        <a-form-model-item label="套餐Id" prop="bizProductItemId" :rules="[{ required: true, trigger: 'change', message: '请填写产品套餐Id' }]">
          <a-input allowClear oninput="value = value.replace(/[^\d]/g, '')" v-model="addBlacklistForm.bizProductItemId" />
        </a-form-model-item>
        <a-form-model-item label="抖音号" prop="douyinId" :rules="[{ required: true, trigger: 'change', message: '请填写抖音号' }]">
          <a-input allowClear v-model="addBlacklistForm.douyinId" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
        :pageSize="pagination.pageSize"
        v-model="pagination.pageIndex"
        :total="pagination.total"
        showQuickJumper
        showLessItems
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px auto;"
        @change="handlePageChange"
      />
    </div>
  </a-spin>
</template>

<script>
import { pointLocationList, getBlacklistElse, addBlacklist, pullBlackReleaseBlacklist, downloadTemplate, uploadBlackList } from '@/service'
import moment from 'moment'
import debounce from 'lodash/debounce'
import { getExcel } from '@/util'
export default {
  name: 'blacklist',
  data() {
    // 节流
    this.getAllStation = debounce(this.getAllStation, 800)
    return {
      moment,
      // 黑名单导入
      file: null,
      confirmLoading: false,
      fileVisible: false,
      //   新增产品弹窗状态
      addBlacklistVisible: false,
      addBlacklistForm: {
        douyinId: '',
        bizProductId: null,
        bizProductItemId: ''
      },
      // loading是否显示
      isLoading: false,
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      // 全部站点
      allStation: [],
      // table数据查询条件
      search: {
        locationId: null, // 站点id
        bizProductId: null, // 产品id
        douyinId: '' // 抖音号
      },
      // 黑名单列表
      blacklist: [],
      tableColumns: [
        { title: '产品ID', width: 76, dataIndex: 'bizProductId' },
        { title: '套餐ID', width: 76, dataIndex: 'bizProductItemId' },
        { title: '抖音号', width: 120, dataIndex: 'douyinId' },
        { title: 'CPS分佣比例', width: 120, dataIndex: 'cps' },
        { title: '状态', width: 120, scopedSlots: { customRender: 'result' } },
        { title: '操作人', width: 120, dataIndex: 'opUser' },
        { title: '操作', width: 100, dataIndex: 'action', scopedSlots: { customRender: 'action' } }
      ]
    }
  },

  methods: {
    // 确认拉黑
    async confirmBlock(id) {
      let data = await pullBlackReleaseBlacklist({ id: id })
      // console.log(res)
      if (data === '') {
        this.$messageSend.success('操作成功')
      } else {
        this.$messageSend.warning(data)
      }
      this.initQuery()
    },
    // 取消拉黑
    cancelBlock() {
      this.$messageSend.warning('已取消')
    },
    async confirmRelieve(id) {
      let data = await pullBlackReleaseBlacklist({ id: id })
      if (data === '') {
        this.$messageSend.success('操作成功')
      }
      this.initQuery()
    },
    cancelRelieve() {
      this.$messageSend.warning('已取消')
    },
    //   新增产品
    handleAddBlacklist() {
      this.$refs.addBlacklistForm.validate(async (valid) => {
        if (valid) {
          let { bizProductId, douyinId, bizProductItemId } = this.addBlacklistForm
          let data = await addBlacklist({ bizProductId, douyinId, bizProductItemId })
          if (data === '') {
            this.$messageSend.success('操作成功')
          } else {
            this.$messageSend.warning(data)
          }
          this.addBlacklistVisible = false
          this.addBlacklistForm = {
            douyinId: '',
            bizProductId: null,
            bizProductItemId: ''
          }
          this.$refs.addBlacklistForm.resetFields()
          this.initQuery()
        } else {
          return false
        }
      })
    },
    // 关闭新增弹窗
    addClose() {
      this.addBlacklistForm = {
        douyinId: '',
        bizProductId: null,
        bizProductItemId: ''
      }
      this.$refs.addBlacklistForm.resetFields()
    },

    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.pagination.pageIndex = 1
      this.setPath(this.getParams())
      this.query()
    },

    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.pagination.pageIndex = num
      this.query()
    },

    getAllStation(e) {
      pointLocationList({ city: e }).then((res) => {
        this.allStation = res
      })
    },
    // 选择了站点
    changeLocation() {
      this.initQuery()
    },
    // 拿参数
    getParams() {
      const { pageIndex, pageSize } = this.pagination
      const { locationId, bizProductId, douyinId } = this.search
      return {
        pageIndex,
        pageSize,
        bizProductId,
        locationId,
        douyinId
      }
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, bizProductId, douyinId } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          ...this.search,
          pageIndex: pageIndex ? Number(pageIndex) : 1,
          bizProductId: bizProductId || null,
          douyinId: douyinId || ''
        }
      }
    },
    // 初始化
    initQuery() {
      this.pagination.pageIndex = 1
      this.pagination.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },
    /**
     * @returns {Promise<void>}
     */
    query() {
      this.isLoading = true
      getBlacklistElse(this.getParams())
        .then((rs) => {
          console.log(rs)
          this.blacklist = Object.freeze(rs.listData) || []
          this.pagination.total = rs.total || 0
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key]) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },

    // 下载模版
    async handleDownloadTemplate() {
      let res = await downloadTemplate()
      window.location.href = res
    },
    // 选择文件
    inputFileChange(e) {
      this.file = e.target.files[0]
    },
    // 确认导入
    handleOk() {
      this.confirmLoading = true
      if (this.file) {
        let formData = new FormData()
        formData.append('file', this.file)
        uploadBlackList(formData)
          .then((_res) => {
            getExcel('黑名单返回结果.xlsx', _res)
            this.initQuery()
          })
          .catch((err) => {
            console.log(err)
          })
        this.$messageSend.success('导入成功，请等后台返回结果')
        setTimeout(() => {
          this.fileVisible = false
          this.confirmLoading = false
          this.$refs.xlsFile.value = ''
        }, 800)
      } else {
        setTimeout(() => {
          this.$messageSend.warning('请选择黑名单文件')
          this.confirmLoading = false
        }, 400)
      }
    },
    // 关闭对话框
    handleCancel() {
      this.$refs.xlsFile.value = ''
    }
  },

  mounted() {
    this.setSearch()
    // 获取所有站点
    pointLocationList({ city: '' })
      .then((res = []) => {
        this.allStation = res
      })
      // 获取失败依然继续请求列表数据
      .catch((err) => err)

    this.initQuery()
  }
}
</script>

<style lang="less" scoped>
.live-review {
  padding: 16px;
}

.color-f55 {
  color: #f55f4e !important;
}
.search-box {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  flex-wrap: wrap;
  > div {
    margin-right: 15px;
    margin-bottom: 5px;
  }
}
.multi-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; // 超出两行则以...形式隐藏
  -webkit-box-orient: vertical;
}
.statu_box {
  display: flex;
  // justify-content: space-between;
  align-items: flex-start;
}
.zt_discrible_btn {
  position: relative;
  left: 5px;
  color: #0090ff;
  cursor: pointer;
}

.zt_discrible_solution_list {
  list-style: none;
}
</style>
